<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-2-25
 * Time: 下午2:42
 */
namespace backend\controllers;

use common\models\JurisdGroup;
use common\models\JurisdUser;
use common\models\Menu;
use common\service\ConstantService;
use common\service\MenuService;
use common\service\LogaddService;

class PermissionController extends BaseController {

    /**
     * 获取权限组列表
     * @return string
     */
    public function actionIndex(){
        if($this->isAjax() && $this->isGet()){
            $rows = JurisdGroup::find()->asArray()->all();
            return $this->renderPageJson($rows,count($rows),ConstantService::$response_tab_success);
        }
        return $this->render('index');
    }

    /**
     * 添加权限组
     * @return string|void
     */
    public function actionAddGroup(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
//            $row = JurisdGroup::findOne(['group_name'=>$data['group_name']]);
            $row = JurisdGroup::find()->where(['group_name'=>$data['group_name']])->one();
            if(!empty($row)){
                return $this->renderJson([],'已经存在同名角色',ConstantService::$response_fail);
            }

            $data['group_mech'] = 1;
            $data['created_at'] = time();
            $data['updated_at'] = time();
            $data['group_jurisd_id'] = implode($data['group_jurisd_id'],',');
            $data['created_at'] = time();
            $data['updated_at'] = time();

            $jurisd_model = new JurisdGroup();
            $jurisd_model->setAttributes($data);
            if($jurisd_model->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'新增权限组'.$data['group_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'添加成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'添加失败',ConstantService::$response_fail);
            }
        }else{
            $menus = Menu::find()->orderBy(['sort' => SORT_ASC])->asArray()->all();
            $menus = MenuService::getCategory($menus);
            return $this->render('add-group',['menus'=>$menus]);
        }
    }

    /**
     * 修改权限组列表
     */
    public function actionUpdateGroup(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $data['group_jurisd_id'] = implode($data['group_jurisd_id'],',');

            $row = JurisdGroup::find()->where(['group_name'=>$data['group_name']])->one();
            if(!empty($row) && $row['group_id'] != $data['group_id']){
                return $this->renderJson([],'已经存在同名的角色名',ConstantService::$response_fail);
            }
            $Juride_row = JurisdGroup::find()->where(['group_id'=>$data['group_id']])->one();
            $data['updated_at'] = time();
            $Juride_row->setAttributes($data);
            if($Juride_row->save(0)){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改权限组'.$Juride_row['group_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'修改失败',ConstantService::$response_fail);
        }else{
            $group_id = $this->get('id');
            $perm = JurisdGroup::find()->where(['group_id'=>$group_id])->asArray()->one();
            $menu_ids = explode(',',$perm['group_jurisd_id']);
            $menus = Menu::find()->orderBy(['sort' => SORT_ASC])->asArray()->all();
            $perms = MenuService::addCheckStatus($menus,$menu_ids);
            $perms = MenuService::getCategory($perms);
            return $this->render('update-group',['data'=>$perm,'perms'=>$perms]);
        }
    }

    /**
     * 删除权限组列表
     */
    public function actionDelGroup(){
        //需要提示如果删除该权限组将删除所有与之相关的用户权限组
        if($this->isPost() && $this->isAjax()){
            $group_id = $this->post('id');
            $perm = JurisdGroup::find()->where(['group_id'=>$group_id])->one();
            $perm->delete();
            //删除关连用户权限
            JurisdUser::deleteAll("group_id=:group_id",['group_id'=>$group_id]);
            $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'删除权限组'.$perm['group_name'];
            LogaddService::logAdd($this->admin['username'],$str);
            return $this->renderJson([],'删除成功',ConstantService::$response_success);

        }
        return $this->renderJson([],'操作不合法',ConstantService::$response_fail);
    }

    /**
     * 根据角色id获取权限树
     */
    public function actionGetPerms(){
        if($this->isAjax() && $this->isPost()){
            $group_id = $this->post('id');
            if(empty($group_id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $row = JurisdGroup::find()->where(['group_id'=>$group_id])->asArray()->one();
            if(!empty($row['group_jurisd_id'])){
                $menu_ids = explode(',',$row['group_jurisd_id']);
            }else{
                $menu_ids = [];
            }
            $menus = Menu::find()->asArray()->all();

            $perms = MenuService::addCheckStatus($menus,$menu_ids);
            $perms = MenuService::getCategory($perms);
            $box_class = [
                1=>'contbox',
                2=>'contbox contbox2',
                3=>'contbox contbox3'
            ];

            $input_class = [
                1=>'listO',
                2=>'listT',
                3=>'listTh',
            ];
            $html = '';
            foreach ($perms as $menu){
                if($menu['parent_code'] == 0){
                    $html .= '<div class="content-box">';
                }
                $html .= '<div class="';
                $html .= isset($box_class[$menu['level']]) ?$box_class[$menu['level']]:'';
                $html .= '">';
                $html .= '<input type="checkbox"';
                if($menu['checked'] == 'true'){
                    $html .= 'checked';
                }
                $html .=' name="" id="list'.$menu['menu_id'];
                $html .= '" class="'.isset($input_class[$menu['level']]) ?$input_class[$menu['level']]:'';
                $html .= '" disabled>';
                $html .= '<label for="list'.$menu['menu_id'];
                $html .= '" class="ckboxl">'.$menu["menu_name"].'</label>';
                $html .= '</div>';
                if($menu['parent_code'] == 0){
                    $html .= '</div>';
                }
            }
            $html .= '';
            // 设置响应头信息.
//            header('Content-type: application/json');

//            echo json_encode([
//                'data'  =>  ['html'=>$html],
//                'msg'   =>  '请求成功',
//                'code'  =>  ConstantService::$response_success,
//                "req_id" =>  uniqid(),    // 防止缓存接口.
//            ]);exit;
            return $this->renderJson(['html'=>$html],'请求成功',ConstantService::$response_success);


        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }



}